package v1

import (
	"net/http"
	"hytx_media/pkg/app"
	"hytx_media/pkg/e"
	"hytx_media/service/media_user_service"

	"github.com/astaxie/beego/validation"
	"golang.org/x/crypto/bcrypt"
	"github.com/gin-gonic/gin"
	"hytx_media/service/sms_service"
)

type register struct {
	Phone string `valid:"Required; MaxSize(50)"`
	Code string `valid:"Required; MaxSize(6)"`
	Password string `valid:"Required; MaxSize(50)"`
}

// @Summary 用户注册
// @Produce  json
// @Param phone param string true "phone"
// @Param password param string true "password"
// @Param code param string true "code"
// @Success 200 {string} json
func Register(c *gin.Context)  {
	appG := app.Gin{C: c}
	valid := validation.Validation{}

	phone := c.PostForm("phone")
	password := c.PostForm("password")
	code := c.PostForm("code")

	a := register{Phone: phone, Code:code, Password: password}
	ok, _ := valid.Valid(&a)

	if !ok {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, false)
		return
	}

	// 短信验证
	sms_service := sms_service.SMSValidate{MobilePhone:phone, MsgCode:code}
	isCheck, _ :=sms_service.Check()

	if !isCheck {
		appG.Response(http.StatusOK, e.ERROR_SMS_VALIDATE, false)
		return
	}

	// 加密
	//password, _ = password_hash.Hash(password)

	paswords,err := bcrypt.GenerateFromPassword([]byte(password), 10)

	if err != nil {
		appG.ResponseMsg(http.StatusOK, "注册失败,密码生成错误", false)
		return
	}
	// 注册Add
	media_user_service := media_user_service.MediaUser{Phone:phone, Password:string(paswords), Status:1}
	if err := media_user_service.Add(); err != nil {
		appG.ResponseMsg(http.StatusOK, "注册失败", false)
		return
	}

	appG.ResponseMsg(http.StatusOK, "ok", true)
}

